package com.yingxue.demo.controller;

import com.yingxue.demo.constant.Constant;
import com.yingxue.demo.entity.User;
import com.yingxue.demo.exception.BizException;
import com.yingxue.demo.exception.enums.UnauthorizedExceptionEnum;
import com.yingxue.demo.service.UserService;
import com.yingxue.demo.util.ResultVOUtil;
import com.yingxue.demo.vo.req.LoginReqVO;
import com.yingxue.demo.vo.resp.LoginRespVO;
import com.yingxue.demo.vo.resp.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Package: com.company.scaffold.controller
 * @Author: Mr.Waves
 * @Date: 2020-03-18 01:07
 * @Description:
 **/
@Api(tags = "用户模块接口")
@RestController
@RequestMapping("api")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation(value = "用户登录接口")
    @PostMapping("user/login")
    public ResultVO<LoginRespVO> login(@RequestBody LoginReqVO loginReqVO) {
        return ResultVOUtil.success(userService.login(loginReqVO));
    }

    @ApiOperation(value = "用户登出接口")
    @GetMapping("user/logout")
    public ResultVO logout(HttpServletRequest request) {
        String accessToken = request.getHeader(Constant.ACCESS_TOKEN);
        String refreshToken = request.getHeader(Constant.REFRESH_TOKEN);
        userService.logout(accessToken, refreshToken);
        return ResultVOUtil.success(null);
    }

    @ApiOperation(value = "引导客户端去登录")
    @GetMapping("user/unLogin")
    public ResultVO unLogin() {
        return ResultVOUtil.error(UnauthorizedExceptionEnum.TOKEN_INVALID);
    }

    @ApiOperation(value = "用户详情查询接口")
    @RequiresPermissions("sys:user:get")
    @GetMapping("user/{id}")
    public ResultVO<User> getUserById(@PathVariable(value = "id") Long id) {
        User user = userService.getUserById(id);
        if (null == user) {
            throw new BizException(LoginExceptionEnum.ACCOUNT_NOT_EXIST);
        }
        return ResultVOUtil.success(user);
    }
}
